<template>
  <el-form-item :label="prop.name" :prop="prop.id">
    <template slot="label">
      <rva-form-config :prop="prop"></rva-form-config>
    </template>
    <el-card shadow="always">
      <el-collapse v-model="activeCollapseItems">
        <el-collapse-item v-for="(row, rowIndex) in formDataList"
          :key="prop.id + '_' + rowIndex" :name="rowIndex"
      >
        <template v-if="row.create">
          <template slot="title">
            <el-tag type="danger" style="margin-right: 10px">新</el-tag>
            <el-tag
                v-if="row[prop.relatedCrudViewData.create.viewData.properties[1].id]"
                type="info" style="margin-right: 10px">{{ row[prop.relatedCrudViewData.create.viewData.properties[1].id] }}</el-tag>
            <el-button size="mini" type="text" @click.stop="addRow(prop.relatedCrudViewData.create.formData, rowIndex)" class="el-icon-plus"> 新增</el-button>
            <el-button size="mini" type="text" @click.stop="removeRow (rowIndex)" class="el-icon-minus" v-show="showRemove()"> 删除</el-button>
          </template>
          <el-row v-for="(row1, row1Index) in createRowsPropData(prop.relatedCrudViewData.create.viewData)" :key="rowIndex + '_' + row1Index">
            <el-col v-for="(col1, col1Index) in row1.cols" :span="col1.colSpan" :key="rowIndex + '_' + row1Index + '_' + col1Index">
              <el-row v-for="(row2, row2Index) in col1.rows" :key="rowIndex + '_' + row1Index + '_' + col1Index + '_' + row2Index">
                <el-col v-for="(col2, col2Index) in row2.cols" :span="col2.span" style="margin-bottom: 20px"
                        :key="rowIndex + '_' + row1Index + '_' + col1Index + '_' + row2Index + '_' + col2Index">
                  <component :is="'rva-form-' + col2.prop.type" v-model="formData[prop.id][rowIndex][col2.prop.id]" :prop="col2.prop"
                             :formData="formData[prop.id][rowIndex]" :ref="col2.prop.id + '_' + rowIndex"
                             :formItemProp="prop.id + '[' + rowIndex + '].' + col2.prop.id"
                             :requestParams="requestParams">
                  </component>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
        <template v-else>
          <template slot="title">
            <el-tag v-if="row.del != 'Y'" type="info" style="margin-right: 10px">{{ row[prop.relatedCrudViewData.update.viewData.properties[1].id] }}</el-tag>
            <el-badge v-else value="删">
              <el-tag type="info" style="margin-right: 10px">{{ row[prop.relatedCrudViewData.update.viewData.properties[1].id] }}</el-tag>
            </el-badge>
            <el-button size="mini" type="text" @click.stop="addRow(prop.relatedCrudViewData.create.formData, rowIndex)" class="el-icon-plus"> 新增</el-button>
            <el-button size="mini" type="text" @click.stop="removeRowUpdate(row)" v-show="showRemove()" class="el-icon-minus"> 删除</el-button>
          </template>
          <el-row v-for="(row1, row1Index) in createRowsPropData(prop.relatedCrudViewData.update.viewData)" :key="rowIndex + '_' + row1Index">
            <el-col v-for="(col1, col1Index) in row1.cols" :span="col1.colSpan" :key="rowIndex + '_' + row1Index + '_' + col1Index">
              <el-row v-for="(row2, row2Index) in col1.rows" :key="rowIndex + '_' + row1Index + '_' + col1Index + '_' + row2Index">
                <el-col v-for="(col2, col2Index) in row2.cols" :span="col2.span" style="margin-bottom: 20px"
                        :key="rowIndex + '_' + row1Index + '_' + col1Index + '_' + row2Index + '_' + col2Index">
                  <component :is="'rva-form-' + col2.prop.type" v-model="formData[prop.id][rowIndex][col2.prop.id]"
                             :prop="col2.prop" :formData="formData[prop.id][rowIndex]" :ref="col2.prop.id + '_' + rowIndex"
                             :formItemProp="prop.id + '[' + rowIndex + '].' + col2.prop.id"
                             :requestParams="requestParams">
                  </component>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-collapse-item>
      </el-collapse>
    </el-card>
  </el-form-item>
</template>

<script>
import RvaFormTextfield from "@/components/rva/form/textfield";
import RvaFormNumberfield from "@/components/rva/form/numberfield";
import RvaFormTextarea from "@/components/rva/form/textarea";
import RvaFormButton from "@/components/rva/form/button";
import RvaFormSelector from "@/components/rva/form/selector";
import RvaFormRadio from "@/components/rva/form/radio";
import RvaFormSelect from "@/components/rva/form/select";
import RvaFormCheckbox from "@/components/rva/form/checkbox";
import {RvaUtils} from "@/api/rva/util";
import {createRowsPropData} from "@/api/rva/crud";

export default {
  name: "RvaFormCrud",
  props: ['prop', 'value', 'formRef', 'formData', 'requestParams'],
  components: {
    "rva-form-button": RvaFormButton,
    "rva-form-textfield": RvaFormTextfield,
    "rva-form-numberfield": RvaFormNumberfield,
    "rva-form-textarea": RvaFormTextarea,
    "rva-form-selector": RvaFormSelector,
    "rva-form-radio": RvaFormRadio,
    "rva-form-select": RvaFormSelect,
    "rva-form-checkbox": RvaFormCheckbox,
  },
  data() {
    return {
      formDataList: [],
      formDataListOld: [],
      disabled: false,
      activeCollapseItems: [0,1,2,3,4]
    };
  },
  created() {
    console.log ('-------rva-form-crud created...');
    this.formDataList = this.formData[this.prop.id];
    // this.prop.formRequired == 'Y'
    if (this.formDataList.length > 1) {
      this.formDataList.pop();
    }
    for (var i in this.formDataList) {
      if (this.formDataList[i].create) {
        this.activateCollapseItems(i);
        break;
      }
    }
    // 将第一个createForm激活（展开）
    for (var i in this.formDataList) {
      if (this.formDataList[i].create) {
        this.activateCollapseItems(i);
        break;
      }
    }
  },
  mounted() {
    console.log ('-------rva-form-crud mounted...');
    for (var i in this.formDataList) {
      let formData = this.formDataList[i];
      if (formData.del == 'Y') {
        continue;
      }
      RvaUtils.trigger(formData, undefined, this.getViewData(formData), this.$refs, i);
    }
    this.formDataListOld = RvaUtils.cloneDeep(this.formDataList);

  },
  methods: {
    activateCollapseItems(index) {
      if (this.activeCollapseItems.indexOf(index) < 0) {
        this.activeCollapseItems.push(index);
      }
    },
    addRow (row, rowIndex) {
      row = RvaUtils.clone(row, {create: true}, true);
      // this.formDataList.splice(rowIndex + 1, 0, row);
      // this.activeCollapseItems(rowIndex + 1);
      this.formDataList.push (row);
      this.activateCollapseItems(this.formDataList.length - 1);
      // 此处必须使用setTimeout，因为$refs可能没有立刻生成
      // var me = this;
      this.$nextTick(() => {
        // RvaUtils.trigger(row, undefined, me.prop.relatedCrudViewData.create.viewData, me.$refs, rowIndex + 1);
        RvaUtils.trigger(row, undefined, this.prop.relatedCrudViewData.create.viewData, this.$refs, this.formDataList.length - 1);
        this.formDataListOld = RvaUtils.cloneDeep(this.formDataList);
      })
      console.log ('this.formData[this.prop.id]', this.formData[this.prop.id]);
    },
    removeRow (rowIndex) {
      this.formDataList.splice(rowIndex, 1);
      this.formDataListOld = RvaUtils.cloneDeep(this.formDataList);
    },
    removeRowUpdate (row) {
      row.del = 'Y';
      this.rerender();
    },
    rerender () {
      // 触发控件重新渲染
      this.formDataList.push([]);
      this.formDataList.pop();
    },
    showRemove () {
      let data = this.formData[this.prop.id];
      return (this.prop.formRequired == 'Y' && data.filter(r => r.del != 'Y').length > 1) || this.prop.formRequired == 'N';
    },
    getViewData(formData) {
      console.log ('this.prop.relatedCrudViewData', this.prop.relatedCrudViewData);
      return formData.create ? this.prop.relatedCrudViewData.create.viewData: this.prop.relatedCrudViewData.update.viewData;
    },
    createRowsPropData (viewData) {
      return createRowsPropData(viewData);
    }
  },
  watch: {
    'formDataList' : {
      handler (val, valOld) {
        console.log ('watch:formDataList-start', val, valOld);
        if (valOld !== val || val.length != this.formDataListOld.length) {// created初始化时触发
          return;
        }
        this.$nextTick(() => {
          for (var i in this.formDataList) {
            let row = this.formDataList[i];
            let rowOld = this.formDataListOld[i];
            if (JSON.stringify(row) == JSON.stringify(rowOld)) {
              continue;
            }
            RvaUtils.trigger(row, rowOld, this.getViewData(row), this.$refs, i);
          }
          this.formDataListOld = RvaUtils.cloneDeep(this.formDataList);
          console.log ('watch:formDataList-end', val, valOld);
        });
      },
      deep: true
    }
  }
};
</script>
